{% extends 'layout/pure_manage.html' %}
{% load dashboard %}
{% load project %}
{% load issues %}
{% load static %}
{% block title %}{% endblock %}

{% block css %}
    <link rel="stylesheet" href="{% static 'web/plugin/editor-md/css/editormd.min.css' %}">
    <link rel="stylesheet" href="{% static 'web/plugin/bootstrap-datepicker/css/bootstrap-datepicker.min.css' %}">
    <link rel="stylesheet" href="{% static 'web/plugin/bootstrap-select/css/bootstrap-select.min.css' %}">
    <link rel="stylesheet" href="{% static 'web/plugin/select2/css/select2.min.css' %}">

    <style>

        .elementList2 {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 8em;
        {#overflow: hidden;#} overflow: scroll;
            overflow-x: hidden;
            z-index: 1;
        }

        .elementList2Task {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
        {#overflow: hidden;#} overflow: scroll;
            z-index: 1;
            word-wrap: break-word;
            word-break: break-all;
            text-overflow: ellipsis;
        }

        .elementList2 ul {
            margin: 0;
            padding: 0
        }

        .elementList2 ul li {
            width: 100%;
            height: 25px;
            line-height: 25px;
            text-indent: 15px;
            border-bottom: 1px dashed #ccc;
            color: #666;
            cursor: pointer;
        {#overflow: hidden;#} overflow: scroll;
            overflow-x: hidden;
            change: expression(
              this.onmousedown=function(){
                this.style.background="#F2F5EF";
              },
              this.onmousedown=function(){
                this.style.background="";
              }
             )
        }

        .elementListTask {
            position: relative;
            width: 604px;
            height: 127px;
            z-index: 1;
            background: #FFF;
            border: 1px solid #000;
            margin-top: -100px;
            display: none;
            text-overflow: ellipsis;
        {#word-break: normal;#}
        }

        .elementList {
            position: relative;
            width: 204px;
            height: 127px;
            z-index: 1;
            background: #FFF;
            border: 1px solid #000;
            margin-top: -100px;
            display: none;
        }

        .switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 17px;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            -webkit-transition: .4s;
            transition: .4s;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            -webkit-transition: .4s;
            transition: .4s;
        }

        input:checked + .slider {
            background-color: #2196F3;
        }

        input:focus + .slider {
            box-shadow: 0 0 1px #2196F3;
        }

        input:checked + .slider:before {
            -webkit-transform: translateX(26px);
            -ms-transform: translateX(26px);
            transform: translateX(26px);
        }

        /* Rounded sliders */
        .slider.round {
            border-radius: 34px;
        }

        .slider.round:before {
            border-radius: 50%;
        }

        {% comment %}   .switch {
               position: relative;
               display: inline-block;
               width: 60px;
               height: 34px;
           }

           .switch input {
               opacity: 0;
               width: 0;
               height: 17px;
           }

           .slider {
               position: absolute;
               cursor: pointer;
               top: 0;
               left: 0;
               right: 0;
               bottom: 0;
               background-color: #ccc;
               -webkit-transition: .4s;
               transition: .4s;
           }

           .slider:before {
               position: absolute;
               content: "";
               height: 26px;
               width: 26px;
               left: 4px;
               bottom: 4px;
               background-color: white;
               -webkit-transition: .4s;
               transition: .4s;
           }

           input:checked + .slider {
               background-color: #2196F3;
           }

           input:focus + .slider {
               box-shadow: 0 0 1px #2196F3;
           }

           input:checked + .slider:before {
               -webkit-transform: translateX(26px);
               -ms-transform: translateX(26px);
               transform: translateX(26px);
           }

           /* Rounded sliders */
           .slider.round {
               border-radius: 34px;
           }

           .slider.round:before {
               border-radius: 50%;
           }
{% endcomment %}

        .issues-list .number {
            width: 100px;
            text-align: right;
        }

        .issues-list .number a {
            font-weight: 500;
            padding: 0 10px;
        }

        .issues-list .issue .tags {
            padding: 10px 0;
        }

        .issues-list .issue .tags span {
            margin-right: 20px;
            display: inline-block;
            font-size: 12px;
        }

        .issues-list .issue .tags .type {
            color: white;
            padding: 1px 5px;
            border-radius: 5px;
            background-color: #dddddd;
        }

        .editormd {
            margin-bottom: 0;
        }

        .pd-0 {
            padding: 0 !important;
        }

        /* 筛选 */
        .filter-area .item {
            margin-bottom: 15px;
        }

        .filter-area .item .title {
            padding: 5px 0;
        }

        .filter-area .item .check-list a {
            text-decoration: none;
            display: inline-block;
            min-width: 65px;
        }

        .filter-area .item .check-list label {
            font-weight: 200;
            font-size: 13px;
            margin-left: 3px;
        }

        .filter-area .item .check-list a:hover {
            font-weight: 300;
        }

        .filter-area .item .check-list .cell {
            margin-right: 10px;
        }

        .Radio input:disabled + label { /*禁用的指针*/
            cursor: not-allowed
        }

        .Radio input {
            display: none
        }

        .Radio label {
            padding: 0 16px 0 0;
            display: inline-block;
            cursor: pointer;
            position: relative
        }

        .Radio label:before {
            box-sizing: border-box;
            content: "";
            width: 18px;
            height: 18px;
            border-radius: 50%;
            border: 1px solid #999;
            margin: 0 8px;
            vertical-align: middle;
            display: inline-block;
            transition: 0.1S;
        }

        .Radio label:hover:before {
            border-color: #00a4ff;
        }

        .Radio input:disabled + label:before {
            background-color: #CCC;
            border-color: #999;
            opacity: 0.5;
        }

        .Radio input:disabled + label {
            opacity: 0.5;
        }

        .Radio input:checked + label:before {
            border: 5px solid #00a4ff;
        }

        .HoverLabel label {
            display: block;
            border-radius: 4px;
            padding: 4px;
            width: 100%;
        }

        .HoverLabel label:hover {
            background-color: #EEE;
        }

        .issues-list .issue .tags .type {
            color: white;
            padding: 1px 5px;
            border-radius: 5px;
            background-color: #dddddd;
        }

        .issues-list .issue .tags .type_primary {
            color: white;
            padding: 1px 5px;
            border-radius: 5px;
            background-color: #007bff;
        }

        .issues-list .issue .tags .type_warning {
            color: white;
            padding: 1px 5px;
            border-radius: 5px;
            background-color: #ffc107;
        }

        .issues-list .issue .tags .type_success {
            color: white;
            padding: 1px 5px;
            border-radius: 5px;
            background-color: #28a745;
        }

        .issues-list .issue .tags .type_danger {
            color: white;
            padding: 1px 5px;
            border-radius: 5px;
            background-color: #dc3545;
        }

        .issues-list .issue .tags .type_info {
            color: white;
            padding: 1px 5px;
            border-radius: 5px;
            background-color: #17a2b8;
        }
    </style>
{% endblock %}

{% block content %}
    <audio id="notifyAudio" hidden="hidden">
        <source src="{% static 'web/audio/notify.mp3' %}" type="audio/mpeg">
        您的浏览器不支持 audio 与元素。
    </audio>

    <div class="container-fluid" style="margin-top: 20px">
        {#    <button type="button" class="layui-btn demo-class-accept" lay-options="{accept: 'file'}">#}
        {#    <i class="layui-icon layui-icon-upload"></i>#}
        {#    上传文件#}
        {#  </button>#}
        <div class="row">
            <div class="col-md-5" style="float: right">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <i class="fa fa-pie-chart" aria-hidden="true"></i>
                        个人工作统计
                        <span class="Radio">
                        <input onclick="mydayTrigger(this.value)" id="day1" name="day" type="radio" value="day1"/><label
                                for="day1">当天</label>
                        <input onclick="mydayTrigger(this.value)" id="day7" name="day" type="radio" value="day7"
                        /><label for="day7">近七天</label>
                        <input onclick="mydayTrigger(this.value)" id="day30" name="day" type="radio"
                               value="day30"/><label for="day30">本月</label>
                        <input onclick="mydayTrigger(this.value)" id="day0" name="day" type="radio" value="day0"/><label
                                for="day0">不限</label>
                    </span>
                        {#                        <label class="fa! switch">#}
                        {#                            <input type="checkbox" id="mytaskToggle" onclick="mytaskTrigger()">#}
                        {#                            <span class="slider round"></span>#}
                        {#                        </label>#}
                        {#                        只看与我相关#}
                    </div>

                    <div class="panel-body">
                        <div id="chart" style="width:100%;min-height:400px">

                        </div>
                    </div>

                </div>
            </div>

            <div class="col-sm-7" id="tasklist">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <i class="fa fa-tasks" aria-hidden="true"></i> 当前我的任务
                        <label class="fa! switch">
                            <input type="checkbox" id="myAttentionToggle" onclick="myAttentionTrigger()">
                            <span class="slider round"></span>
                        </label>
                        包含我关注的
                        <button type="button" class="layui-btn layui-btn-primary layui-border-blue"
                                lay-on="open-chat-room">打开聊天室
                        </button>
                    </div>
                    <form method="get" action="{% url 'workbench' project_id=request.web.project.id %}">
                        <div class="input-group">
                                 <span class="input-group-btn">
                         <button class="btn btn-default" type="submit">搜索</button>
                     </span>
                            <input onclick="setF(this)" type="text" name="q" class="form-control"
                                   placeholder="Search for..." value={{ value }}>
                            <span class="input-group-btn">
                         <button class="btn btn-default" type="submit">搜索</button>
                     </span>
                        </div>
                    </form>


                    <!-- Table -->
                    <table class="table">
                        <tbody class="issues-list">
                        {% for item in issues_object_list %}
                            <tr>
                                <td class="number">
                                    <i class="fa fa-circle text-{{ item.priority }}"></i>
                                    <a target="_blank"
                                       href="{% url 'issues_detail' project_id=request.web.project.id issues_id=item.issue_id %}">#{{ item.issue_id }}</a>
                                </td>
                                <td class="issue">
                                    <div>
                                        <a target="_blank"
                                           href="{% url 'issues_detail' project_id=request.web.project.id issues_id=item.issue_id %}">{{ item.subject }}</a>
                                    </div>
                                    <div class="tags">
                            <span class="
                                    {% if item.status == 1 %}
                                            type_primary
                                            {% elif item.status == 2 %}
                                             type_warning
                                            {% elif item.status == 3 %}
                                            type_success
                                            {% elif item.status == 4 %}
                                            type_danger
                                            {% elif item.status == 5 %}
                                            type_info
                                   {% else %}type{% endif %}">
                                        {{ item.issues_type }}
                                <i class="fa fa-refresh" aria-hidden="true"></i>
                            {{ item.get_status_display }}
                                    </span>
                                        {#                            <span>#}
                                        {##}
                                        {#                                    </span>#}
                                        {% if item.assign.username %}
                                            <span>
                                        <i class="fa fa-hand-o-right" aria-hidden="true"></i>
                                        {{ item.assign.username }}
                                    </span>
                                        {% endif %}
                                        <span>
                                        <i class="fa fa-user-o" aria-hidden="true"></i>
                                        {{ item.creator.username }}
                                    </span>
                                        {% if item.end_date %}
                                            <span>
                                        <i class="fa fa-calendar" aria-hidden="true"></i>
                                        {{ item.end_date }} 截止
                                    </span>
                                        {% endif %}
                                        <span>
                                        <i class="fa fa-clock-o" aria-hidden="true"></i>
                                        {{ item.latest_update_datetime }} 更新
                                    </span>
                                    </div>
                                </td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
                <nav aria-label="...">
                    <ul class="pagination" style="margin-top: 0px">
                        {{ page_html|safe }}
                    </ul>
                </nav>

            </div>


        </div>
        <input id="csrf_token" value="{{ csrf_token }}" hidden="hidden"/>
        <input id="days" value="{{ days }}" hidden="hidden"/>
        <input id="fresh_counts" value="{{ fresh_counts }}" hidden="hidden"/>
        <input id="handle_counts" value="{{ handle_counts }}" hidden="hidden"/>
        <input id="resolve_counts" value="{{ resolve_counts }}" hidden="hidden"/>
        <input id="wait_counts" value="{{ wait_counts }}" hidden="hidden"/>
        <input id="reopen_counts" value="{{ reopen_counts }}" hidden="hidden"/>
        <input id="project_id" value="{{ request.web.project.id }}" hidden="hidden"/>
        <input id="user_id" value="{{ request.web.user.id }}" hidden="hidden"/>
        <input id="username" value="{{ request.web.user.username }}" hidden="hidden"/>
        <input id="all_object_list" value="{{ all_object_list }}" hidden="hidden"/>
        <input id="user_list" hidden="hidden"/>
    </div>
{% endblock %}

{% block js %}

    <script src="{% static 'web/plugin/table2excel/jquery.table2excel.min.js' %}"></script>
    <script src="{% static 'web/js/peerjs.min.js' %}"></script>
    <script>

      var user_id = eval(document.getElementById("user_id").value);

        function setF(the) {
            this.focus()
        }

        Date.prototype.pattern = function (fmt) {
            var o = {
                "M+": this.getMonth() + 1, //月份
                "d+": this.getDate(), //日
                "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
                "H+": this.getHours(), //小时
                "m+": this.getMinutes(), //分
                "s+": this.getSeconds(), //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds() //毫秒
            };
            var week = {
                "0": "周日",
                "1": "周一",
                "2": "周二",
                "3": "周三",
                "4": "周四",
                "5": "周五",
                "6": "周日"
            };
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            if (/(E+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "") : "") + week[this.getDay() + ""]);
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            return fmt;
        }

        const myAttentionTriggerKey = "myAttentionTrigger" + '{{ request.web.user.id }}' + '_' + '{{ request.web.project.id }}'
        console.log('myAttentionTriggerKey', myAttentionTriggerKey)

        const mydayTriggerKey = "mydayTrigger" + '{{ request.web.user.id }}' + '_' + '{{ request.web.project.id }}'
        console.log('mydayTriggerKey', mydayTriggerKey)

        const legendTriggerKey = "legendTrigger" + '{{ request.web.user.id }}' + '_' + '{{ request.web.project.id }}'
        console.log('legendTriggerKey', legendTriggerKey)

        function myAttentionTrigger() {
            console.log("myAttentionTrigger")
            let isChecked = $('input[type="checkbox"]').prop('checked');
            if (isChecked) {
                console.log("勾选");
                localStorage.setItem((user_id+'_'+project_id)+myAttentionTriggerKey, "on")
            } else {
                console.log("未勾选");
                localStorage.setItem((user_id+'_'+project_id)+myAttentionTriggerKey, "off")
            }
            sendFreshTriggerVal()
        }

        {% comment %}   function storageTriggerInit() {

           }{% endcomment %}


        function sendFreshTriggerVal() {
            $.ajax({
                url: "{% url 'attention_cache' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "trigger": localStorage.getItem((user_id+'_'+project_id)+myAttentionTriggerKey),
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    console.log(res);
                    if (res.code) {
                        console.log("reload")
                        location.reload();
                    } else {

                    }
                }

            })
        }


        let userlist_online = []

        {#调整为当天，近七天，近一月，近三个月相关数据展示#}
        {#当天的切换为漏洞图#}
        var myChart = echarts.init(document.getElementById("chart"));
        var days = eval(document.getElementById("days").value);
        var fresh_counts = eval(document.getElementById("fresh_counts").value);
        var handle_counts = eval(document.getElementById("handle_counts").value);
        var resolve_counts = eval(document.getElementById("resolve_counts").value);
        var wait_counts = eval(document.getElementById("wait_counts").value);
        var reopen_counts = eval(document.getElementById("reopen_counts").value);
        var project_id = eval(document.getElementById("project_id").value);

        var all_object_list = eval(document.getElementById("all_object_list").value)
        var username = document.getElementById("username").value;

        var all_object_ids = all_object_list.map(o => o[0])
        console.log(all_object_ids)
        var tasks = ['task']
        for (d in days) {
            tasks.push(days[d])
        }
        console.log('tasks', tasks)
        myChart.showLoading();
        // setTimeout(function () {
        option = {
            title: {
                left: 8,
                top: 100,
                text: '默认展示当天饼图',
                textStyle: {
                    fontSize: 7
                }

            },
            legend: {
                selected: {
                    '已解决': false
                }
            },
            tooltip: {
                trigger: 'axis',
                showContent: false,

            },
            dataZoom: [
                {
                    show: true,
                    realtime: true,
                    start: 30,
                    end: 70,
                    xAxisIndex: [0, 1]
                },
                {
                    type: 'inside',
                    realtime: true,
                    start: 30,
                    end: 70,
                    xAxisIndex: [0, 1]
                }
            ],
            toolbox: {
                orient: 'vertical', //水平显示(vertical为垂直显示)
                {#x: '', //距离X轴多远#}
                feature: {
                    dataView: {
                        show: true, readOnly: false,
                        lang: ['{{ request.web.user.username }} ' + getDayPlainTag((user_id+'_'+project_id)+localStorage.getItem(mydayTriggerKey)) + ' ' + '工作量视图', '关闭', '导出excel'],
                        contentToOption: function (opts) {
                            $("#worktasksTable").table2excel({           // 下载jquery.table2excel.js，引入，$("#tempChart")是Echarts容器
                                exclude: ".noExl", //过滤位置的 css 类名， 有class = “noExl” 的行不被导出
                                filename: '{{ request.web.user.username }}_' + getDayPlainTag((user_id+'_'+project_id)+localStorage.getItem(mydayTriggerKey)) + '_工作量视图' + new Date().pattern("yyyy-MM-dd_EE_HH_mm_ss") + ".xls", // 文件名称
                                name: '{{ request.web.user.username }}_' + getDayPlainTag((user_id+'_'+project_id)+localStorage.getItem(mydayTriggerKey)) + '_工作量视图' + new Date().pattern("yyyy-MM-dd_EE_HH_mm_ss"),
                                exclude_img: true,
                                exclude_links: true,
                                exclude_inputs: true
                            });
                        },
                        optionToContent: function (opt) {
                            console.log('opt', opt);
                            var tdHeads = '<td  style="padding:0 10px">{{ request.web.user.username }}</td>';
                            var axisData = opt.dataset[0].source;
                            for (var i = 1; i < axisData[0].length; i++) {
                                tdHeads += '<td style="padding: 0 10px">' + axisData[0][i] + '</td>';
                            }
                            var table = '<table id="worktasksTable" border="1" style="margin-left:20px;border-collapse:collapse;font-size:14px;text-align:center;"><tbody><tr>' + tdHeads + '</tr>';
                            var tdBodys = '';
                            for (var i = 1, l = axisData.length; i < l; i++) {
                                for (var j = 0; j < axisData[i].length; j++) {
                                    tdBodys += '<td>' + axisData[i][j] + '</td>';
                                }
                                {#table += '<tr><td style="padding: 0 10px">' + axisData[i] + '</td>' + tdBodys + '</tr>';#}
                                table += '<tr>' + tdBodys + '</tr>';
                                tdBodys = '';
                            }
                            table += '</tbody></table>';
                            return table;
                        },

                    },
                    magicType: {show: true, type: ['line', 'bar']},
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },
            dataset: {
                source: [
                    tasks,
                    fresh_counts,
                    reopen_counts,
                    handle_counts,
                    wait_counts,
                    resolve_counts
                ]
            },
            xAxis: {
                type: 'category',
                axisLabel: {
                    show: true, // 是否显示刻度标签，默认显示
                    interval: 'auto', // 坐标轴刻度标签的显示间隔，在类目轴中有效；默认会采用标签不重叠的策略间隔显示标签；可以设置成0强制显示所有标签；如果设置为1，表示『隔一个标签显示一个标签』，如果值为2，表示隔两个标签显示一个标签，以此类推。
                    rotate: 0, // 刻度标签旋转的角度，在类目轴的类目标签显示不下的时候可以通过旋转防止标签之间重叠；旋转的角度从-90度到90度
                    inside: false, // 刻度标签是否朝内，默认朝外
                    margin: 6, // 刻度标签与轴线之间的距离
                    {#formatter: '{value} Day', // 刻度标签的内容格式器#}
                }
            },
            yAxis: {
                gridIndex: 0,
                axisLabel: {
                    formatter: '{value}项',
                    align: 'right'
                }
            },
            grid: {top: '55%'},
            {#markLine: { data: [ {type: 'average', name: '平均值'} ] },#}
            series: [
                {
                    type: 'line',
                    smooth: true,
                    seriesLayoutBy: 'row',
                    emphasis: {focus: 'series'}
                },
                {
                    type: 'line',
                    smooth: true,
                    seriesLayoutBy: 'row',
                    emphasis: {focus: 'series'}
                },
                {
                    type: 'line',
                    smooth: true,
                    seriesLayoutBy: 'row',
                    emphasis: {focus: 'series'}
                },
                {
                    type: 'line',
                    smooth: true,
                    seriesLayoutBy: 'row',
                    emphasis: {focus: 'series'}
                },
                {
                    type: 'line',
                    smooth: true,
                    seriesLayoutBy: 'row',
                    emphasis: {focus: 'series'},
                    selected: false,
                },
                {
                    type: 'pie',
                    id: 'pie',
                    radius: '30%',
                    center: ['50%', '25%'],
                    emphasis: {
                        focus: 'self'
                    },
                    label: {
                        formatter: '{b}: {@c} ({d}%)'
                    },
                    encode: {
                        itemName: 'task',
                        value: days[0],
                        tooltip: ''
                    }
                }
            ]
        };

        myChart.on('updateAxisPointer', function (event) {
            console.log('event ', event)
            let xAxisIndex = myChart.length;
            console.log('xAxisIndex', xAxisIndex)
            const xAxisInfo = event.axesInfo[0];
            console.log('xAxisInfo ', xAxisInfo)
            if (xAxisInfo) {
                const dimension = xAxisInfo.value + 1;
                myChart.setOption({
                    series: {
                        id: 'pie',
                        label: {
                            {#formatter: '{b}: {@[' + dimension + ']} ({d}%)'#}
                        },
                        encode: {
                            value: dimension,
                            tooltip: dimension
                        }
                    }
                });
            }
        });
        myChart.setOption(option);
        myChart.hideLoading();
        myChart.on("click", function (params) {
            console.log(params);
            if (params.name && params.seriesName) {
                console.log('click ')
                console.log('params.name ', params.name)
                console.log('params.seriesName ', params.seriesName)


            }
        });
        myChart.on("mousemove", function (params) {
            console.log(params);
            if (params.name && params.seriesName) {
                console.log('mousemove ')
                console.log('params.name ', params.name)
                console.log('params.seriesName ', params.seriesName)

                {#window.location.href = "/manage/" + pid + "/issues/?status=" + (yMatchTypes.indexOf(params.name) + 1) +#}
                {#    "&issues_type=" + (issues_types[(xMatchTypes.indexOf(params.seriesName))])#}
            }
        });
        myChart.on("mouseout", function (params) {
            console.log(params);
            if (params.name && params.seriesName) {
                console.log('mouseout')
                console.log('params.name ', params.name)
                console.log('params.seriesName ', params.seriesName)

                {#window.location.href = "/manage/" + pid + "/issues/?status=" + (yMatchTypes.indexOf(params.name) + 1) +#}
                {#    "&issues_type=" + (issues_types[(xMatchTypes.indexOf(params.seriesName))])#}
            }
        });

        myChart.on('legendselectchanged', function (e) {
            if (e.selected[e.name]) {
                // 点击项是选中状态
                console.log(e.name + ' checked')
                sendFreshEchartLegendTriggerVal(e.selected)
            } else {
                // 点击项是取消状态
                console.log(e.name + ' un checked')
                sendFreshEchartLegendTriggerVal(e.selected)
            }
        });


        function mydayTrigger(val) {
            console.log("mydayTrigger", val)
            sendFreshDayTriggerVal(val)
        }

        // });
        function sendFreshDayTriggerVal(val) {
            $.ajax({
                url: "{% url 'day_cache' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "trigger": val,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    console.log(res);
                    if (res.code) {
                        localStorage.setItem((user_id+'_'+project_id)+mydayTriggerKey, val)
                        location.reload();
                    } else {

                    }
                }

            })
        }

        function sendFreshEchartLegendTriggerVal(val) {
            let reqVal = ''
            if (val.新建) {
                reqVal += 1
            }
            if (val.处理中) {
                reqVal += 2
            }
            if (val.重新打开) {
                reqVal += 3
            }
            if (val.待反馈) {
                reqVal += 4
            }
            if (val.已解决) {
                reqVal += 5
            }
            if (!reqVal) {
                alert('至少保留一项😄')
                location.reload();
                return
            }
            console.log(reqVal)
            $.ajax({
                url: "{% url 'echart_legend_cache' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "trigger": reqVal,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    console.log('sendFreshEchartLegendTriggerVal res', res);
                    if (res.code) {
                        localStorage.setItem((user_id+'_'+project_id)+legendTriggerKey, reqVal)
                        console.log("reload")
                        {#legendTriggerRefresh()#}
                        {#reloadWorkBenchJson()#}
                        location.reload();
                        {#$("#tasklist").load(issues_object_list=[])#}
                    } else {

                    }
                }

            })
        }


        function reloadWorkBenchJson() {
            $.ajax({
                url: "{% url 'workbench_json' %}",
                type: "POST",
                data: {
                    "project_id": project_id,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    console.log('res:', res);
                    {#alert(res)#}
                    if (res.code) {
                        {#localStorage.setItem(mydayTriggerKey, val)#}
                        console.log("reload")
                        {#location.reload();#}
                        {#$("#tasklist").html(res)#}
                    } else {

                    }
                }

            })
        }

        function legendTriggerRefresh() {
            let legend = localStorage.getItem((user_id+'_'+project_id)+legendTriggerKey);
            console.log('legendTriggerRefresh le>>', legend);
            let legendArr = ['新建', '处理中', '重新打开', '待反馈']
            if (!legend) {
                legend = '1234'
                localStorage.setItem((user_id+'_'+project_id)+legendTriggerKey, legend);
            } else {
                if (legend) {
                    let splitLegend = legend.split("");
                    for (var i = 0; i < 5; i++) {
                        myChart.setOption({
                            legend: {selected: {[legendArr[i]]: false}},
                        })
                    }
                    for (s in splitLegend) {
                        if (splitLegend[s] == '1') {
                            myChart.setOption({
                                legend: {selected: {['新建']: true}}
                            })
                        } else if (splitLegend[s] == '2') {
                            myChart.setOption({
                                legend: {selected: {['处理中']: true}}
                            })
                        } else if (splitLegend[s] == '3') {
                            myChart.setOption({
                                legend: {selected: {['重新打开']: true}}
                            })
                        } else if (splitLegend[s] == '4') {
                            myChart.setOption({
                                legend: {selected: {['待反馈']: true}}
                            })
                        } else if (splitLegend[s] == '5') {
                            myChart.setOption({
                                legend: {selected: {['已解决']: true}}
                            })
                        }
                    }

                } else {
                    console.log('legendTriggerKey', legend)
                    {% comment %}     for (var i = 0; i < 5; i++) {
                             myChart.setOption({
                                 legend: {selected: {[legendArr[i]]: false}},
                             })
                         }{% endcomment %}
                }
            }
        }

        function storageTriggerInit() {
            let day = localStorage.getItem((user_id+'_'+project_id)+mydayTriggerKey);
            console.log('day', day);
            if (day) {
                document.getElementById(day).setAttribute('checked', true);
            } else {
                day = 'day7'
                localStorage.setItem((user_id+'_'+project_id)+mydayTriggerKey, day);
                document.getElementById(day).setAttribute('checked', true);
            }
            legendTriggerRefresh()

            let item = localStorage.getItem((user_id+'_'+project_id)+myAttentionTriggerKey);
            if (!item) {
                item = 'off'
                localStorage.setItem((user_id+'_'+project_id)+myAttentionTriggerKey, item);
            } else {
                console.log("myAttentionTrigger", item)
                if (item == "on") {
                    $('input[type="checkbox"]').prop('checked', true);
                } else {
                    $('input[type="checkbox"]').prop('checked', false);
                }
            }
        }


        storageTriggerInit()

        {#ws聊天室相关 below：#}
        {#$('#page_header').text('聊天室');#}
        {#$('#page_header_descript').text('chat room');#}

        function chatRoomSetup() {
            websocketInit()
            $("#chatMembers").html($("#user_list").val())
            {#websocketInit()#}
            document.querySelector('#chat-message-input').focus();
            document.querySelector('#chat-message-input').onkeyup = function (e) {
                if (e.keyCode === 13) {  // enter, return
                    document.querySelector('#chat-message-submit').click();
                }
            };

            document.querySelector('#chat-message-input').change = function (e) {
                console.log('msg input change:', e)
            }
            document.querySelector('#chat-message-submit').onclick = function (e) {
                var messageInputDom = document.querySelector('#chat-message-input');
                var message = messageInputDom.value;
                if (!message) {
                    console.log('message can not be empty')
                    return
                }
                console.log('message', message)
                if (message.startsWith('http')) {
                    console.log('transfer to _blank a')
                    message = "<a href=" + message + " target='_blank'" + ">" + message + "</a>"
                }
                let stringifyMsg = JSON.stringify({
                    'message': message,
                    'type': 'normal'
                });
                let atMembersConfirm = []
                if (atMemberFlag) {
                    console.log('atMemberFlag', atMemberFlag)
                    for (m in atMemberNames) {
                        if (message.indexOf('@' + atMemberNames[m]) > -1) {
                            console.log('confirm hint user ', atMemberNames[m])
                            atMembersConfirm.push(atMemberNames[m])
                        }
                    }
                    if (atMembersConfirm.length > 0 && !atTaskFlag) {
                        //send hint msg
                        stringifyMsg = JSON.stringify({
                            'message': message,
                            'type': 'hint',
                            'receivers': atMembersConfirm,
                            'sender': '{{ request.web.user.username }}'
                        });
                    }
                }

                if (atTaskFlag) {
                    console.log('atTaskFlag', atTaskFlag)
                    let atTasksConfirm = []
                    for (t in atTaskIds) {
                        if (message.indexOf('#' + atTaskIds[t]) > -1) {
                            console.log('confirm hint task ', atTaskIds[t])
                            atTasksConfirm.push(atTaskIds[t])
                        }
                    }

                    if (atTasksConfirm.length > 0) {
                        let task_message = ''
                        for (t in atTasksConfirm) {
                            let taskid = atTasksConfirm[t]
                            const request_detail_url = "{% url 'issues_detail' project_id=request.web.project.id issues_id=1 %}".replace("detail/1", "detail/" + taskid)
                            task_message = "<a href=" + request_detail_url + " target='_blank'>" + message + "</a>"
                            break;
                        }
                        //send hint msg
                        console.log('atMembersConfirm', atMembersConfirm)
                        console.log('atTasksConfirm ', atTasksConfirm)
                        stringifyMsg = JSON.stringify({
                            'message': task_message,
                            'type': atMemberFlag ? 'hint' : 'normal',
                            'receivers': atMemberFlag ? atMembersConfirm : [],
                            'sender': '{{ request.web.user.username }}'
                        });
                    }
                }

                console.log(stringifyMsg)

                if (isOnlineCurrUser()) {
                    let send = ws.send(stringifyMsg);
                    console.log('send', send)
                    messageInputDom.value = '';
                    atMemberNames = []
                    atTaskIds = []
                    atMemberFlag = false
                    atTaskFlag = false
                } else {
                    console.log('reconnect ws...')
                    createOrConnectWebSocket()
                    var count = 0
                    while (!isOnlineCurrUser() && count < 100) {
                        count++
                        {#createOrConnectWebSocket()#}
                        console.log('reconnect ws 3')
                    }
                    console.log('ws.send(stringifyMsg)', stringifyMsg)
                    let send = ws.send(stringifyMsg);
                    console.log('send', send)
                    messageInputDom.value = '';
                    atMemberNames = []
                    atTaskIds = []
                    atMemberFlag = false
                    atTaskFlag = false
                }
            };


            function chatHisInit() {

                let mychatLog = localStorage.getItem((user_id+'_'+project_id)+'mychatLog' + project_id)
                {#console.log('mychatLog>>',mychatLog);#}
                if (mychatLog && mychatLog != 'undefined') {
                    document.querySelector('#chat-log').innerHTML += (mychatLog);
                    document.querySelector('#chat-log').scrollTop = document.querySelector('#chat-log').scrollHeight;
                }
            }

            chatHisInit()
        }


        function closeInputChooseElements() {
            $("#atMembers").hide()
            $("#atTasks").hide()
            {#document.querySelector('#chat-message-input').focus();#}
        }

        let atMemberFlag = false
        let atTaskFlag = false
        let atMemberNames = []
        let atTaskIds = []

        function msginputOnchange(evt, ipt) {
            console.log('msg input change:', evt.target.selectionStart)
            const cursorPosition = evt.target.selectionStart
            let text = ipt.value
            const textBfCursor = text.substring(0, cursorPosition)
            const lastChar = textBfCursor.charAt(textBfCursor.length - 1)
            $("#atMembersUl > li").remove()
            console.log('lastChar ', lastChar)
            if (lastChar === '@') {
                if (userlist_online.length > 0) {
                    $("#atMembers").show()
                    let ul = $("#atMembersUl")
                    for (var u in userlist_online) {
                        let element = document.createElement("li");
                        element.setAttribute('onmousedown', 'getValue("chat-message-input", "' + userlist_online[u] + '","member")')
                        var m = document.createTextNode(userlist_online[u]);
                        element.appendChild(m);
                        console.log(element)
                        ul.append(element)
                    }
                }
            } else if (lastChar === '#') {
                if (atTaskIds.length > 0) {
                    alert('一次只能拉取一条task。')
                    return
                }
                if (all_object_list.length > 0) {
                    $("#atTasks").show()
                    let ul = $("#atTasksUl")
                    for (var t in all_object_list) {
                        let element = document.createElement("li");
                        element.setAttribute('onmousedown', 'getValue("chat-message-input", "' + all_object_list[t] + '","task")')
                        var t = document.createTextNode(all_object_list[t]);
                        element.appendChild(t);
                        console.log(element)
                        ul.append(element)
                    }
                }
            } else {
                $("#atMembers").hide()
                $("#atTasks").hide()
                {#atMemberFlag = false#}
                {#atTaskFlag = false#}
            }
            {#document.querySelector('#chat-message-input').focus();#}
        }

        function showAndHide(obj, types) {
            var Layer = window.document.getElementById(obj);
            switch (types) {
                case "show":
                    Layer.style.display = "block";
                    break;
                case "hide":
                    Layer.style.display = "none";
                    break;
            }
        }

        function getValue(obj, str, type) {
            console.log('getvalue')
            var input = window.document.getElementById(obj);
            input.value += str + ' ';
            if (type === 'member') {
                if (atMemberNames.indexOf(str) > -1) {
                    console.log('user indexof has')
                } else {
                    atMemberNames.push(str)
                }
                if (atMemberNames.length > 0) {
                    atMemberFlag = true
                }
                console.log(atMemberNames)
            } else if (type === 'task') {
                taskid = parseInt(str.split(',')[0])
                if (all_object_ids.includes(taskid) && atTaskIds.includes(taskid)) {
                    console.log('task contains')
                } else if (all_object_ids.includes(taskid) && !atTaskIds.includes(taskid)) {
                    atTaskIds.push(taskid)
                }
                if (atTaskIds.length > 0) {
                    atTaskFlag = true
                }
                console.log(atTaskIds)
            }
            document.querySelector('#chat-message-input').focus();
        }

        function isOpen(ws) {
            return ws.readyState === ws.OPEN
        }


        var interval_timer = null;//计时器
        var timer_count = 0;
        const position = 'workbench';
        var wsUrl = 'ws://' + window.location.host + '/chat/ws/' + project_id + '/' + user_id + '/' + username
        var ws;

        createOrConnectWebSocket();	// 创建websocket
        /**
         * 创建websocket或掉线重连
         */
        function createOrConnectWebSocket() {
            var count = 0
            if (!ws) {
                ws = new WebSocket(wsUrl);
                websocketInit();
            } else {
                if (!isOnlineCurrUser() && count < 100) {
                    count++
                    ws = null;
                    createOrConnectWebSocket();
                }
            }
            // 开启定时器
            init_start_timer();
        }

        let chatUserList = []

        /**
         * websocket 的初始化
         */
        function websocketInit() {
            ws.onmessage = function (e) {
                console.log('evt e ', e)
                var data = JSON.parse(e.data);
                console.log('>>>>>', data.type)
                if (data.type == 'userlist.message') {
                    let userlistval = eval(data.message);
                    console.log(userlistval)
                    userlist_online = userlistval
                    console.log('userlistmessage refresh userlist ', userlistval.length)
                    var userlist = ''
                    for (let i = 0; i < userlistval.length; i++) {
                        userlist += ` <li>` + userlistval[i] + `</li>`;
                    }
                    chatUserList = userlistval
                    $("#user_list").val(userlist)
                    $("#chatMembers").html(userlist);
                    return
                } else if (data.type == 'private.message') {
                    var message = data['message'];
                    document.querySelector('#chat-log').innerHTML += ('<label style="color: hotpink">' + message + '</label>' + '<br>');
                    localStorage.setItem((user_id+'_'+project_id)+'mychatLog' + project_id, document.querySelector('#chat-log').innerHTML)
                    const notify_audio = document.getElementById('notifyAudio')
                    notify_audio.play();
                    document.querySelector('#chat-log').scrollTop = document.querySelector('#chat-log').scrollHeight;
                    $("#badge").load(location.href + " #badge")

                } else {
                    var message = data['message'];
                    document.querySelector('#chat-log').innerHTML += (message + '<br>');
                    localStorage.setItem((user_id+'_'+project_id)+'mychatLog' + project_id, document.querySelector('#chat-log').innerHTML)
                    document.querySelector('#chat-log').scrollTop = document.querySelector('#chat-log').scrollHeight;
                }
            };
            ws.onclose = function (e) {
                console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
            };

        }

        /**
         * 设置一个 30秒的轮询监听方法，避免页面关闭
         */
        function init_start_timer() {
            //重置计数器
            timer_count = 0;
            if (interval_timer != null) {
                clearInterval(interval_timer);
                interval_timer = null;
            }
            interval_timer = setInterval(function () {
                myTimer()
            }, 10000);
        }

        /**
         *定时器具体实现方法
         */
        function myTimer() {
            // 如果超过半小时没有交互，则关闭计时器
            if (timer_count >= 300000) {
                clearInterval(interval_timer);
            } else {
                timer_count += 30;
                createOrConnectWebSocket()
                console.log('timer_count', timer_count);
            }
        }

        /**
         * 判断当前用户是否 还在线
         */
        function isOnlineCurrUser() {
            if (ws) {
                if (ws.readyState == WebSocket.OPEN) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }


        function getDayPlainTag(dayTrigger) {
            switch (dayTrigger) {
                case 'day1':
                    return "当天";
                case 'day7':
                    return "近七天";
                case 'day30':
                    return "本月";
                case 'day0':
                    return "不限时间";
                default:
                    return ''
            }
        }

        layui.use(function () {
            var upload = layui.upload;
            var element = layui.element;
            var layer = layui.layer;
            var util = layui.util;
            var $ = layui.$;
            // 渲染

            // 事件
            util.on('lay-on', {
                'open-chat-room': function () {
                    {% comment %}var uploadListIns = upload.render({
                        elem: '#ID-upload-demo-files',
                        elemList: $('#ID-upload-demo-files-list'), // 列表元素对象
                        url: '{% url fileupload %}', // 实际使用时改成您自己的上传接口即可。
                        accept: 'file',
                        multiple: true,
                        number: 3,
                        auto: false,
                        bindAction: '#ID-upload-demo-files-action',
                        choose: function (obj) {
                            var that = this;
                            var files = this.files = obj.pushFile(); // 将每次选择的文件追加到文件队列
                            // 读取本地文件
                            obj.preview(function (index, file, result) {
                                var tr = $(['<tr id="upload-' + index + '">',
                                    '<td>' + file.name + '</td>',
                                    '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>',
                                    '<td><div class="layui-progress" lay-filter="progress-demo-' + index + '"><div class="layui-progress-bar" lay-percent=""></div></div></td>',
                                    '<td>',
                                    '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>',
                                    '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>',
                                    '</td>',
                                    '</tr>'].join(''));

                                // 单个重传
                                tr.find('.demo-reload').on('click', function () {
                                    obj.upload(index, file);
                                });

                                // 删除
                                tr.find('.demo-delete').on('click', function () {
                                    delete files[index]; // 删除对应的文件
                                    tr.remove(); // 删除表格行
                                    // 清空 input file 值，以免删除后出现同名文件不可选
                                    uploadListIns.config.elem.next()[0].value = '';
                                });

                                that.elemList.append(tr);
                                element.render('progress'); // 渲染新加的进度条组件
                            });
                        },
                        done: function (res, index, upload) { // 成功的回调
                            var that = this;
                            // if(res.code == 0){ // 上传成功
                            var tr = that.elemList.find('tr#upload-' + index)
                            var tds = tr.children();
                            tds.eq(3).html(''); // 清空操作
                            delete this.files[index]; // 删除文件队列已经上传成功的文件
                            return;
                            //}
                            this.error(index, upload);
                        },
                        allDone: function (obj) { // 多文件上传完毕后的状态回调
                            console.log(obj)
                        },
                        error: function (index, upload) { // 错误回调
                            var that = this;
                            var tr = that.elemList.find('tr#upload-' + index);
                            var tds = tr.children();
                            // 显示重传
                            tds.eq(3).find('.demo-reload').removeClass('layui-hide');
                        },
                        progress: function (n, elem, e, index) { // 注意：index 参数为 layui 2.6.6 新增
                            element.progress('progress-demo-' + index, n + '%'); // 执行进度条。n 即为返回的进度百分比
                        }
                    });{% endcomment %}
                    layer.open({
                        title: '项目聊天室',
                        type: 1,
                        offset: 'b',
                        anim: 'slideUp', // 从下往上
                        area: ['100%', '460px'],
                        shade: 0.1,
                        shadeClose: true,
                        id: 'ID-demo-layer-direction-b',
                        {#id: 'ID-upload-demo-drag',#}
                        {#content: '<div style="padding: 16px;">任意 HTML 内容</div><div></div>',#}
                        content: '<div class="col-md-7" style="float: left">' +
                            '<div class="panel panel-default"><div class="panel-heading">' +
                            '<i class="fa fa-tasks" aria-hidden="true"></i> Team Communicate (@选择提醒用户#选择task)</div><div><div id="chat-log" class="col-md-10" contenteditable="false" style="resize:none;height: 300px;background-color: floralwhite;align:top;overflow: auto;">' +
                            '</div>' +
                            {#'<video id="shareScreen" style="min-height:380px;min-width:600px;width:100%;background-color: #00a8c6">' +#}
                            {#'</video>' +#}
                            '<div class="col-md-2" style="float: right">online用户: <div>' +
                            '<ul id="chatMembers"></ul></div></div></div>' +
                            '<div class="col-md-4" style="float: right;padding-top: 0%">' +
                            '<div id="atMembers" style="position: absolute" class="elementList" hidden="hidden">' +
                            '<ul id="atMembersUl" class="elementList2"></ul></div>' +
                            '<div id="atTasks" style="position: absolute" class="col-xs-4 elementListTask" hidden="hidden"><ul id="atTasksUl" class="elementList2Task"></ul></div>' +
                            '<input id="chat-message-input" oninput="msginputOnchange(event,this)" type="text" placeholder="聊天信息发送" onblur="closeInputChooseElements()"/><br/>' +
                            '<input id="chat-message-submit" class="btn layui-btn" type="button" value="Send (enter)"/></div></div></div>' +

                            '<div class="col-md-5" style="float:right">' +
                            '视频区域 ' +
                            '之后默认全屏视频流<input type="checkbox" name="streamAlways" title="ON|OFF" lay-skin="switch" >' +
                            '<button onclick="leavePeerConn()">关闭视频</button>' +
                            '<button onclick="reConnPeer()">重联视频</button>' +
                            '<video id="peerScreen" onclick="openPeerConn()" style="min-height:380px;min-width:600px;width:100%;background-color: #00a8c6">' +
                            '</video>' +
                            '</div>'

                        {#'<div class="layui-upload">' +#}
                        {#'<button type="button" class="layui-btn layui-btn-normal" id="ID-upload-demo-files">选择多文件</button>' +#}
                        {#'<div class="layui-upload-list">' +#}
                        {#'<table class="layui-table">' +#}
                        {#'<colgroup>' +#}
                        {#'<col style="min-width: 100px;">' +#}
                        {#'<col width="150">' +#}
                        {#'<col width="260">' +#}
                        {#'<col width="150">' +#}
                        {#'</colgroup>' +#}
                        {#'<thead>' +#}
                        {#'<th>文件名</th>' +#}
                        {#'<th>大小</th>' +#}
                        {#'<th>上传进度</th>' +#}
                        {#'<th>操作</th>' +#}
                        {#'</thead>' +#}
                        {#'<tbody id="ID-upload-demo-files-list"></tbody>' +#}
                        {#'</table>' +#}
                        {#'</div>' +#}
                        {#'<button type="button" class="layui-btn" id="ID-upload-demo-files-action">开始上传</button></div>'#}

                    });
                    chatRoomSetup()
                },
                'test-offset-l': function () {
                    layer.open({
                        type: 1,
                        offset: 'l',
                        anim: 'slideRight', // 从左往右
                        area: ['320px', '100%'],
                        shade: 0.1,
                        shadeClose: true,
                        id: 'ID-demo-layer-direction-l',
                        content: '<div style="padding: 16px;">任意 HTML 内容</div>'
                    });
                },
            });
        });
        {% comment %}     document.getElementById("chat-message-input").addEventListener("keydown", function (event) {
                 if ((event.ctrlKey || event.metaKey) && event.keyCode === 13) {
                     layer.msg('发送中')
                     event.preventDefault();
                     // 执行你想要的操作

                 }
             });{% endcomment %}
        var peerId = null

        var peer = null

        function openPeerConn() {
            if (peerId === '{{ request.web.user.username }}' + '_PEER') {
                console.log('peerId exist and right')
                sendUserlistStatus('peeropen', peerId)
            } else {
                peer = new Peer('{{ request.web.user.username }}' + '_PEER', {
                    debug: 2,
                    host: 'localhost',
                    port: 9000,
                    path: 'peer'
                });
                console.log('peer.disconnected', peer.disconnected)
                peer.on('open', function (id) {
                    console.log('My peer ID is: ' + id);
                    peerId = id
                    layer.msg('user {{ request.web.user.username }} on peer')
                    sendUserlistStatus('peeropen', peerId)
                });
                peer.on('close', function () {
                    layer.msg('close')
                    leavePeerConn()
                    sendUserlistStatus('peerclose', peerId)
                });
                peer.on('disconnected', function () {
                    layer.msg('disconnected')
                    leavePeerConn()
                    sendUserlistStatus('peerclose', peerId)
                });
            }
            //获取摄像头instance
            getConnectedDevices('videoinput', cameras => {
                console.log('Cameras found', cameras)
                layer.msg('当前可用的摄像头:' + JSON.stringify(cameras.map(c => c.deviceId)))
                if (cameras) {
                    //开启摄像头
                    navigator.mediaDevices.getUserMedia({
                        video: {
                            width: {min: 1024, max: 1920, ideal: 1280},
                            height: {min: 576, max: 1080, ideal: 720},
                            frameRate: {max: 30}
                        }, audio: true
                    }).then((stream) => {
                        //私屏
                        let video = document.getElementById("peerScreen")
                        video.srcObject = stream;
                        video.onloadedmetadata = () => {
                            video.play();
                        }
                        const call = peer.call(peerId, stream)
                        {% comment %}   call.on('stream', remoteStream => {
                               //公屏
                               const shareScreen = document.getElementById("shareScreen")
                               shareScreen.srcObject = remoteStream
                               shareScreen.onloadedmetadata = () => {
                                   shareScreen.play();
                               }
                           });{% endcomment %}
                    }).catch(err => {
                        console.error('Error accessing media devices.', err)
                    })
                }
            });
            peer.on('data', function (data) {
                console.log('data ', data)
            })
            peer.on('call', function (call) {
                console.log('peer on call ')
                navigator.mediaDevices.getUserMedia({
                    video: {
                        width: {min: 1024, max: 1920, ideal: 1280},
                        height: {min: 576, max: 1080, ideal: 720},
                        frameRate: {max: 30}
                    }, audio: true
                }).then(stream => {
                    //私屏
                    const shareScreen = document.getElementById("shareScreen")
                    shareScreen.srcObject = stream
                    shareScreen.onloadedmetadata = () => {
                        shareScreen.play();
                    }
                    call.answer(stream)
                    call.on('stream', remoteStream => {
                        //公屏
                        const shareScreen = document.getElementById("shareScreen")
                        shareScreen.srcObject = remoteStream
                        shareScreen.onloadedmetadata = () => {
                            shareScreen.play();
                        }
                    });
                }).catch(err => {
                    console.error("on call Error", err)
                })
            })
        }


        function leavePeerConn() {
            peer.disconnect()
            console.log('peer disconnected', peer.disconnected)
            document.getElementById("peerScreen").srcObject = null
        }

        function reConnPeer() {
            console.log('peer disconnected', peer.disconnected)
            peer.reconnect()
            console.log('peer disconnected', peer.disconnected)
            navigator.mediaDevices.getUserMedia({
                video: {
                    width: {min: 1024, max: 1920, ideal: 1280},
                    height: {min: 576, max: 1080, ideal: 720},
                    frameRate: {max: 30}
                }, audio: true
            }).then(stream => {
                //私屏
                let video = document.getElementById("peerScreen")
                video.srcObject = stream;
                video.onloadedmetadata = () => {
                    video.play();
                }
            })
        }

        function connMedia(peerObj) {

        }

        function getConnectedDevices(type, callback) {
            navigator.mediaDevices.enumerateDevices()
                .then(devices => {
                    const filtered = devices.filter(device => device.kind === type);
                    callback(filtered);
                });
        }


        function sendUserlistStatus(status, peerId) {
            layer.msg('sendUserlistStatus')
            $.ajax({
                url: "{% url 'received_userlist_status' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "status": status,
                    "peer_id": peerId,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        layer.msg('发送成功', {icon: 6})

                        {#location.reload();#}
                        {#$("#badge").load(location.href + " #badge")#}
                    } else {
                        layer.msg('发送异常', {icon: 5})
                    }
                }
            })
        }

    </script>


{% endblock %}